package com.leo.anywhereimageview.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;

import static android.content.ContentValues.TAG;

/**
 * Created by yang on 2017/8/6.
 */

public class RoundAngleImageView extends android.support.v7.widget.AppCompatImageView {
    private Paint paint;
    public RoundAngleImageView(Context context) {
        this(context,null);

    }

    public RoundAngleImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public RoundAngleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint=new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable drawable=getDrawable();
        if (drawable!=null){
            Bitmap bit=((BitmapDrawable)drawable).getBitmap();
            Bitmap b=getCircleBitmap(bit,200);
            Log.d(TAG, "onDraw: "+b.getWidth()+""+b.getHeight());
            Rect dst=new Rect(0,0,getWidth(),getHeight());
            Rect src=new Rect(0,0,b.getWidth(),b.getHeight());
            paint.reset();
            canvas.drawBitmap(b,src,dst,paint);
        }else {
            super.onDraw(canvas);
        }
    }

    private Bitmap getCircleBitmap(Bitmap bit, int i) {
        Bitmap bitmap = Bitmap.createBitmap(bit.getWidth(), bit.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas=new Canvas(bitmap);
        Rect rect=new Rect(0,0,bit.getWidth(),bit.getHeight());
        paint.setAntiAlias(true);
        canvas.drawARGB(0,0,0,0);
        paint.setColor(0xff424242);
        int x=bit.getWidth();
        int y=bit.getHeight();
        // canvas.drawRoundRect(new RectF(0,0,x,y),x/4,y/4,paint);
        canvas.drawOval(new RectF(0,0,x,y),paint);
        // canvas.drawCircle(x/2,x/2,x/2,paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bit,rect,rect,paint);
        return bitmap;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}